package root.electronclass.electronclass.grade.homework.viewmodel

import androidx.lifecycle.*
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.ext.NotifyWhenChangeLiveData
import root.electronclass.electronclass.grade.model.*
import root.electronclass.electronclass.grade.repository.ClassRepository
import root.electronclass.electronclass.grade.viewmodel.WeekType

/**
 *
 * @author Lokiy
 * @date 2023/2/4 14:07
 */
class ClassHomeworkStatisticalViewModel : ViewModel() {

    /**
     * -1 上一周 0本周 1下一周
     */
    val selectWeekType = NotifyWhenChangeLiveData(WeekType.CURRENT)
    val selectDayOfWeek = NotifyWhenChangeLiveData(0)
    val selectStatus = NotifyWhenChangeLiveData(0)

    val data: LiveData<List<ClassHomeworkItem>> = selectWeekType.switchMap { type ->
        selectStatus.switchMap { status ->
            selectDayOfWeek.switchMap { dayOfWeek ->
                liveData(CoroutineExceptionHandler { }) {
                    emit(ClassRepository.getClassHomeworkStatistical(dayOfWeek, type, status))
                }
            }
        }
    }

    val subjectStatistical: LiveData<List<Pair<String, Int>>> = selectWeekType.switchMap { type ->
        liveData(CoroutineExceptionHandler(false)) {
            emit(ClassRepository.getClassHomeworkStatistical(0, type, 0)
                .groupBy { it.subject ?: "" }
                .filter { it.key.isNotEmpty() }
                .map { it.key to it.value.size })
        }
    }
}
